package ioc

import (
	"basic-go/syntax/webook/internal/web"
	"basic-go/syntax/webook/internal/web/middleware"
	"basic-go/syntax/webook/pkg/ginx/middleware/ratelimit"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"strings"
	"time"
)

func InitWeb(handlerFunc []gin.HandlerFunc, uhandler *web.UserHandler) *gin.Engine {
	server := gin.Default()
	server.Use(handlerFunc...)
	uhandler.RegisterRoutes(server)
	return server
}

func MiddlwareHandlerFunc(cmd redis.Cmdable) []gin.HandlerFunc {
	return []gin.HandlerFunc{
		CorsFunc(),
		ratelimit.NewBuilder(cmd, time.Minute, 100).Build(),
		(middleware.NewLoginJWTMiddlewareBuilder()).CheckLoginJWT(),
	}
}

func CorsFunc() gin.HandlerFunc {
	return cors.New(cors.Config{
		//AllowAllOrigins:  []string{"http://localhost:3000"},
		AllowCredentials: true,
		AllowHeaders:     []string{"Content-Type", "authorization"},
		// 这个是允许前端访问你的后端响应中带的头部
		ExposeHeaders: []string{"x-jwt-token"},
		AllowOriginFunc: func(origin string) bool {
			println(origin)
			if strings.HasPrefix(origin, "http://localhost") {
				return true
			}
			return strings.Contains(origin, "your_company.com")
		},
		MaxAge: 12 * time.Hour,
	})
}
